/**
 * 
 */
package cn.gov.msa.ws;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.context.ApplicationContext;
import cn.gov.msa.model.DictionaryDetail;
import cn.gov.msa.util.FileUtil;
import cn.gov.msa.util.InfoObjUtil;
import cn.gov.msa.util.PropertiesTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**   
* @Title: FileService.java 
* @Package cn.gov.msa.ws 
* @Description: TODO(用一句话描述该文件做什么) 
* @author 何宇江  
* @date 2018年3月21日 下午6:02:14 
*/
public class FileService {
	
	private static String cmpPath = PropertiesTools.readProperties("project.path") ;

	public static String upload(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = "上传失败！";
	    JSONObject jsonResult = new JSONObject();
		
		try{
        	String dirname = "";
	        JSONObject jsonFile = JSONArray.fromObject(params).getJSONObject(0);
	        
	        cn.gov.msa.service.FileService fileService = (cn.gov.msa.service.FileService) ctx.getBean("FileService"); 
	        
	        if(jsonFile.has("busscode")){
	        	String busscode = jsonFile.getString("busscode");
		        cn.gov.msa.service.DictionaryDetailService dictionaryDetailService = (cn.gov.msa.service.DictionaryDetailService) ctx.getBean("DictionaryDetailService");  
		        
	            DictionaryDetail dictionaryDetail = dictionaryDetailService.selectDataByDictCodeAndItemCode("DM_WJLB", busscode);

	            dirname = dictionaryDetail.getItemname();
	        }
			
	
	        String fileprefixname = jsonFile.getString("filename");
	        String filesuffixname = jsonFile.getString("filesuffix");
	        long filesize = jsonFile.getLong("filesize");
	        String filetype = jsonFile.getString("filetype");
	        
	        FileUtil fileUtil = new FileUtil();
//	        String path = fileUtil.getFilePath() + "upload/" + dirname;
	        String path = cmpPath + "/gahCMP/upload/" + dirname;

	        Date now = new Date( );
	        SimpleDateFormat ft = new SimpleDateFormat("yyyyMMddhhmmssSSS");
	        String uploadFileName = ft.format(now) + '.' + filesuffixname;
	        
	        File targetFile = new File(path, uploadFileName);  
	        
	        String content = jsonFile.getString("content");
	        byte[] b = FileUtil.hexStringToBytes(content);
	        
	        System.out.println(">>>1111111");
	        System.out.println(">>>path" + path);
	        System.out.println(">>>uploadFileName" + uploadFileName);
	        
			FileOutputStream fos = null;
			try {
				if (!targetFile.exists()) {// 文件不存在则创建
					if(!targetFile.getParentFile().exists()) {
						//如果目标文件所在的目录不存在，则创建父目录  
			            System.out.println("目标文件所在目录不存在，准备创建它！");  
			            if(!targetFile.getParentFile().mkdirs()) {  
			                System.out.println("创建目标文件所在目录失败！");  
			            }  
					}
					targetFile.createNewFile();
				}
				fos = new FileOutputStream(targetFile);
				fos.write(b);// 写入文件内容
				fos.flush();

		        System.out.println(">>>22222");
	            String fileurl = "/gahCMP/upload/" + dirname + "/" +uploadFileName;
		        System.out.println(">>>33333" + fileurl);
	            
	            //将上传的文件保存到记录表Pub_File      start
	        	cn.gov.msa.model.File file = new cn.gov.msa.model.File();
	        	file.setFilename(fileprefixname);
	        	file.setFilesize(filesize);
	        	file.setFilesuffix(filesuffixname);
	        	file.setFiletype(filetype);
	        	file.setFileurl(fileurl);
	        	file.setStorecontent(b);
	        	
	        	String fileId = fileService.save(file);
	        	
	            //将上传的文件保存到记录表Pub_File end
	
		        JSONArray jaFile = new JSONArray();
		        
	        	JSONObject joFile = new JSONObject();
	        	joFile.put("fileid", fileId);
	        	joFile.put("filename", fileprefixname + '.' + filesuffixname);
	        	joFile.put("fileurl", fileurl);
	        	jaFile.add(joFile);	
	           
	            JSONObject datas = new JSONObject();	            
	            jsonResult.put("datas", jaFile);
	            result = 1;
	            info = InfoObjUtil.Success_upload_OK;

			} catch (IOException e) {
				e.printStackTrace();
				System.err.println("文件创建失败");
			} finally {
				if (fos != null) {
					try {
						fos.close();
					} catch (IOException e) {
						System.err.println("文件流关闭失败");
					}
				}
			}
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	

	public static String down(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        cn.gov.msa.service.FileService fileService = (cn.gov.msa.service.FileService) ctx.getBean("FileService"); 
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);
	        String fileid = "";
	        if(jsonParams.has("fileid")){
	        	fileid = jsonParams.getString("fileid");
		        cn.gov.msa.model.File file = fileService.selectByPrimaryKey(fileid);
		        
//		        FileUtil fileUtil = new FileUtil();
//		        String filePath = cmpPath + file.getFileurl();
//		        
//		        InputStream input  = new FileInputStream(new File(filePath));
//		        byte[] byt = new byte[input.available()];
//		        input.read(byt);
		        
		        String content = FileUtil.bytesToHexString(file.getStorecontent());
		        jsonResult.put("datas", content);
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
}
